﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Antioch.Base.PlayerStates
{
    internal class HangFromLedge : IState
    {
        public void Enter(StateMachine Machine)
        {
            Machine.DrawComponent.Play("HangLedge", true);
            Machine.PhysicsComponent.PhysicsBody.GetFixtureList().SetFriction(0.0f);
        }

        public void Leave(StateMachine Machine)
        {
            
        }

        private void DetachLedgeHangJoint(StateMachine Machine)
        {
            Machine.PhysicsModule.PhysicsSimulator.DestroyJoint(Machine.Memory.LedgeHangJoint);
            Machine.Memory.LedgeHangJoint = null;
        }

        public void Update(StateMachine Machine)
        {
            if (Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Left && Machine.Input.NavigationStick.X >= 0.1f)
                Machine.Transition(typeof(LookAwayFromLedge));
            else if (Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Right && Machine.Input.NavigationStick.X <= -0.1f)
                Machine.Transition(typeof(LookAwayFromLedge));
            else if (Machine.Input.NavigationStick.Y < 0)
            {
                DetachLedgeHangJoint(Machine);
                Machine.Transition(typeof(Fall));
            }
            else if (Machine.Input.NavigationStick.Y > 0 && Machine.Memory.LedgeHangPoint.CanClimb)
            {
                DetachLedgeHangJoint(Machine);
                Machine.Transition(typeof(ClimbOntoLedge));
            }
            else if (!Machine.Memory.LedgeHangPoint.CanHang(Machine.PlayerEntity))
            {
                DetachLedgeHangJoint(Machine);
                Machine.Transition(typeof(Fall));
            }
            else if (Machine.Memory.LedgeHangJoint.GetReactionForce(1.0f / 60.0f).Length() > 2.0f
                && Machine.TimeInState > 2)
            {
                DetachLedgeHangJoint(Machine);
                Machine.Transition(typeof(Fall));
            }
        }
    }
}
